﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MobileSales.Model.Products;
using MobileSales.Common.Logger;
using MobileSales.Website.Infrastructure.Messaging;
using MobileSales.Model.Params;
using System.ServiceModel;
using MobileSales.Model.Exceptions;
using MobileSales.Website.Infrastructure;
using MobileSales.Website.Localization;


namespace MobileSales.Website.Controllers
{
    [Authorize]
    public class ProductsController : ControllerBase
    {
        #region Index
        //
        // GET: /Products/

        public ActionResult Index(int? categoryId)
        {
            IEnumerable<Product> products = null;
            try
            {
                ProductService.ProductServiceClient productService = new ProductService.ProductServiceClient();
                productService.AddValidationToken(this.Token);
                if (categoryId.HasValue)
                    products = productService.GetProductListByCategory(categoryId.Value);
                else
                    products = productService.GetProductList();
                productService.Close();
            }
            catch (Exception ex)
            {
                CLogger.LogDebug(ex);
                this.SetMessage(ErrorStrings.ErrorProductList, MessageType.Error);
            }
            return View(products);
        } 
        #endregion

        #region Details
        //
        // GET: /Products/Details/5

        public ActionResult Details(int id)
        {
            Product product = null;
            try
            {
                ProductService.ProductServiceClient productService = new ProductService.ProductServiceClient();
                productService.AddValidationToken(this.Token);
                product = productService.GetProduct(id);
                productService.Close();
                return View(product);
            }
            catch (Exception ex)
            {
                CLogger.LogDebug(ex);
                this.SetMessage(InfoStrings.ProductNotFound, MessageType.Error);
                return RedirectToAction("Index");
            }
        } 
        #endregion

        #region Create
        //
        // GET: /Products/Create

        public ActionResult Create()
        {
            return View();
        }

        //
        // POST: /Products/Create

        [HttpPost]
        public ActionResult Create(Product product, FormCollection form)
        {
            try
            {
                product.Params = this.GetParameters(form, ParamType.Product);
                product.Categories = this.GetCategories(form);
                ProductService.ProductServiceClient productService = new ProductService.ProductServiceClient();
                productService.AddValidationToken(this.Token);
                productService.StoreProduct(product);
                productService.Close();
                this.SetMessage(InfoStrings.ProductCreated, MessageType.Info);
                return RedirectToAction("Index");
            }
            catch (FaultException<ValidationException> ex)
            {
                CLogger.LogDebug(ex);
                this.SetMessage(ex.Detail.Message, MessageType.Error);
            }
            catch (Exception ex)
            {
                CLogger.LogDebug(ex);
                this.SetMessage(ErrorStrings.ErrorProductCreating, MessageType.Error);
            }
            return View(product);
        } 
        #endregion

        #region Edit
        //
        // GET: /Products/Edit/5

        public ActionResult Edit(int id)
        {
            return Details(id);
        }

        //
        // POST: /Products/Edit/5

        [HttpPost]
        public ActionResult Edit(int id, Product product, FormCollection form)
        {
            try
            {
                product.Id = id;
                product.Params = this.GetParameters(form, ParamType.Product);
                product.Categories = this.GetCategories(form);
                ProductService.ProductServiceClient productService = new ProductService.ProductServiceClient();
                productService.AddValidationToken(this.Token);
                productService.StoreProduct(product);
                productService.Close();
                this.SetMessage(InfoStrings.ProductUpdated, MessageType.Info);
                return RedirectToAction("Index");
            }
            catch (FaultException<ValidationException> ex)
            {
                CLogger.LogDebug(ex);
                this.SetMessage(ex.Detail.Message, MessageType.Error);
            }
            catch (Exception ex)
            {
                CLogger.LogDebug(ex);
                this.SetMessage(ErrorStrings.ErrorProductUpdating, MessageType.Error);
                
            }
            return View(product);
        }

        #region GetCategories
        private IList<Category> GetCategories(FormCollection form)
        {

            string[] stringValues = (string[])form.GetValue("CategoryIds").RawValue;
            stringValues = stringValues.Where(x => !string.IsNullOrEmpty(x)).ToArray();
            IEnumerable<int> ids = stringValues != null ? stringValues.Select(x => int.Parse(x)) : new List<int>();
            if (ids.Count()>0)
            {
                ProductService.ProductServiceClient productService = new ProductService.ProductServiceClient();
                productService.AddValidationToken(this.Token);
                IList<Category> result = productService.GetCategoryList(ids.ToArray()).ToList();
                productService.Close();
                return result;
            }
            return null;
        }  
        #endregion

        #endregion

        #region Delete
        //
        // GET: /Products/Delete/5

        public ActionResult Delete(int id)
        {
            return Details(id);
        } 

        //
        // POST: /Products/Delete/5

        [HttpPost]
        public ActionResult Delete(int id, FormCollection collection)
        {
            try
            {
                ProductService.ProductServiceClient productService = new ProductService.ProductServiceClient();
                productService.AddValidationToken(this.Token);
                productService.RemoveProduct(id);
                productService.Close();
                this.SetMessage(InfoStrings.ProductDeleted, MessageType.Info);
                return RedirectToAction("Index");
            }
            catch (FaultException<ValidationException> ex)
            {
                CLogger.LogDebug(ex);
                this.SetMessage(ex.Detail.Message, MessageType.Error);
            }
            catch (Exception ex)
            {
                CLogger.LogDebug(ex);
                this.SetMessage(ErrorStrings.ErrorProductDeleting, MessageType.Error);
            }
            return RedirectToAction("Index");
        }
        #endregion
    }
}
